package com.hyjr.RxTask.work;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.hyjr.RxTask.rabbitmq.ProducerUtil;
import com.hyjr.RxTask.rabbitmq.RabbitmqConstants;
import com.hyjr.RxTask.work.service.ConsumerWork;
import com.hyjr.bean.AccountBean;
import com.hyjr.bean.CheckBean;
import com.hyjr.bean.TaskBean;
import com.hyjr.common.enums.AccountStateEnum;
import com.hyjr.common.enums.CheckStateEnum;
import com.hyjr.common.enums.FailFalgEnum;
import com.hyjr.common.utils.LogUtils;
import com.hyjr.common.utils.Utils;

public class TaskScheduleWork implements ConsumerWork {
	private static TaskScheduleWork _netReceiver = null;

	public static TaskScheduleWork GetInstance() {
		if (_netReceiver == null) {
			_netReceiver = new TaskScheduleWork();
		}
		return _netReceiver;
	}

	@Override
	public void doWork(String message) throws Exception {
		LogUtils.debug("检测端，TaskScheduleWork线程，从任务队列中读取数据，任务数据：" + message);
		
		TaskBean taskBean = JSON.parseObject(message, TaskBean.class);
		
		String[] checkTypeArr = taskBean.getCheckTypes().split(",");
		
		//解析账号信息
		String[] accountStrArr = taskBean.getDecrFileInfo().split("\n");
		List<AccountBean> accountBeanList = new ArrayList<AccountBean>();
		List<CheckBean> checkBeanList = new ArrayList<CheckBean>();
		for(String accountStr : accountStrArr) {
			String[] accountItemArr = accountStr.split(":");
			if(accountItemArr.length > 2) {
				AccountBean accountBean = new AccountBean();
				accountBean.setAccountId(Utils.getUUID());
				accountBean.setTaskId(taskBean.getTaskId());
				accountBean.setAccountName(accountItemArr[0]);
				accountBean.setEncrPwd(accountItemArr[1]);
				accountBean.setAccountState(AccountStateEnum.WAIT.getKey());
				accountBean.setCheckCnt(checkTypeArr.length);
				accountBean.setFailCnt(0);
				
				accountBeanList.add(accountBean);
				
				for(String checkType : checkTypeArr) {
					CheckBean checkBean = new CheckBean();
					checkBean.setCheckId(Utils.getUUID());//检测ID
					checkBean.setTaskId(taskBean.getTaskId());//所属任务ID
					checkBean.setAccountId(accountBean.getAccountId());//所属账号ID
					checkBean.setCheckType(checkType);//检测类型
					checkBean.setCheckState(CheckStateEnum.WAIT.getKey());//检测状态
					checkBean.setFailFalg(FailFalgEnum.SUCCESS.getKey());//失败标识
					checkBean.setFailCnt(0);//失败次数
					checkBeanList.add(checkBean);
					
					//将检测任务放入相应的检查队列中
					ProducerUtil.producer(RabbitmqConstants.CHECK_DISTR_PRE + checkType, checkBean);
					LogUtils.debug("检测端，TaskScheduleWork线程，将需要检测数据放入队列中，检测类型：" + checkType + "，检测数据：" + checkBean);
				}
			}
		}
		
		taskBean.setCheckAccountCnt(accountBeanList.size());
		taskBean.setFailAccountCnt(0);
		taskBean.setReceivedTime(new Date());
	}
}
